import React,{useState,useEffect, useCallback} from 'react'
import {useSearchParams,useNavigate} from 'react-router-dom'
import request,{baseUrl} from '../utils/request'
import {Image,NavBar,ImageViewer,Grid,Ellipsis } from 'antd-mobile'
import {StarOutline,HeartOutline} from 'antd-mobile-icons'
function Goods(){
    // url参数（?后面的参数传递id）: /goods?id=123
    const [params] = useSearchParams()
    const id = params.get('id')
    const [goods,setGoods] = useState({})

    // 添加id作为依赖，解决同页面跳转问题
    useEffect(()=>{
        getData()
    },[id])
    const getData = async()=>{
        // http://120.76.247.5:2003/api/goods/+id
        const { data } = await request.get('/goods/'+id)
        console.log('data',data)


        setGoods(data.data)
    }
    const navigate = useNavigate()
    const back = useCallback(()=>{
        navigate(-1)
    },[])

    // 大图显示
    const [visible,setVisible] = useState(false)
    const showBigImage = ()=>{
        setVisible(true)
    }

    // 同类热门商品
    const [hotlist,setHotlist] = useState([])
    const getList = async ()=>{
        if(!goods.category) return;
        const { data } = await request.get('/goods/',{
            params:{
                category:goods.category,
                sort:'views'
            }
        })
        setHotlist(data.data.result)
    }
    useEffect(()=>{
        getList()
    },[goods])

    const gotoDetail = useCallback((id)=>{
        navigate('/goods?id='+id)
    },[])

    return <div>
        <NavBar onBack={back} right={<HeartOutline fontSize={24} />}>{goods.goods_name}</NavBar>
        <Image src={baseUrl + goods.img_url} onClick={showBigImage} />
        <h1 style={{fontSize:18}}>{goods.goods_name}</h1>
        <p className='price'><del>{goods.price}</del><span>{goods.sales_price}</span></p>
        <p>已售：{goods.sales_qty}</p>

        <h3>同类热门商品</h3>
        <Grid columns={2} gap={18}>
            {
                hotlist.map(item => (
                    <Grid.Item key={item._id} onClick={gotoDetail.bind(null,item._id)}>
                        <Image src={baseUrl + item.img_url} width="100%" />
                        <Ellipsis content={item.goods_name} rows={3} expandText="展开" collapseText="收起">

                        </Ellipsis>

                        <p className='price'><del>{item.price}</del><span>{item.sales_price}</span></p>
                    </Grid.Item>

                ))
            }
        </Grid>

        <ImageViewer
            image={baseUrl + goods.big_img_url}
            visible={visible}
            defaultIndex={1}
            onClose={() => {
                setVisible(false)
            }}
        />
    </div>
}

export default Goods;